package com.chuji.crmcj.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.MagClientLoseDetailActivity;
import com.chuji.crmcj.bean.MagClientLoseInfo;
import com.chuji.crmcj.bean.SureLoseReadInfo;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

import java.util.ArrayList;
import java.util.List;

public class MagClientLoseFragment extends Fragment {
    //客户战报列表
    private ListView mLv_client_lose;
    /*自定义适配器*/
    private CustomClientLoseAdapter customClientLoseAdapter;
    /*数据存储*/
    List<MagClientLoseInfo.ApiParamObjEntity> magClientLoseData;
    /*网络数据*/
    private MagClientLoseInfo magClientLoseInfo;
    /*确认已读*/
    private SureLoseReadInfo sureLoseReadInfo;
    //用户ID
    String UserID;
    String MessageID;
    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.fragment_client_lose, container, false);

        mLv_client_lose = (ListView) view.findViewById(R.id.lv_client_lose);
        //得到UserID
        UserID= SPUtils.getString(UIUtils.getContext(),"UserID","");
//        //初始化适配器
//        customClientLoseAdapter=new CustomClientLoseAdapter();
//        //数据
//
//        //填充
//        mLv_client_lose.setAdapter(customClientLoseAdapter);
        initData();
        return view;
    }
    public void initData() {
        /**
         * 获得评价记录
         */
        getAppraiseData();
    }
    private void getAppraiseData() {
        //第一次
        if (magClientLoseData == null) {
            magClientLoseData = new ArrayList<MagClientLoseInfo.ApiParamObjEntity>();
        }
        requestData();
    }
    private void requestData() {
        //初始化Volley
        String strURL = String.format(UrlUtils.GET_MAG_CLIENT_LOSE+"&UserID="+UserID+"&defeatType=1"+"&pageSize="+"3"+"&currentPage=1");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                magClientLoseInfo = JSON.parseObject(response, MagClientLoseInfo.class);
                magClientLoseData.addAll(magClientLoseInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断adapter是否创建
                        if (customClientLoseAdapter == null) {
                            customClientLoseAdapter = new CustomClientLoseAdapter();
                            mLv_client_lose.setAdapter(customClientLoseAdapter);
                        } else {
                            customClientLoseAdapter.notifyDataSetChanged();
                        }
                        //给ListView设置点击事件
                        mLv_client_lose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                if(magClientLoseData.get(position).getIsRead().equals("0")){
                                    SureRead(UserID,"战败审批",magClientLoseData.get(position).getDefeatApproveID());
                                }
                                //传递战败申请ID
                                Intent intent=new Intent(UIUtils.getContext(), MagClientLoseDetailActivity.class);
                                intent.putExtra("DefeatApproveID",magClientLoseData.get(position).getDefeatApproveID());
                                startActivity(intent);
                            }
                        });
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    public void SureRead(String UserID,String Remark,String BusinessId){
        String strURL = String.format(UrlUtils.SUBMIT_Lose_ISREAD+"&UserID="+UserID+"&Remark="+Remark+"&BusinessId="+BusinessId);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                sureLoseReadInfo = JSON.parseObject(response,SureLoseReadInfo.class);
                if(sureLoseReadInfo.getApiParamObj().get(0).getIsok().equals("0")){
                    UIUtils.showToastSafe("消息已读");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    /**
     * 自定义适配器
     */
    class CustomClientLoseAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return magClientLoseData.size();
        }

        @Override
        public Object getItem(int position) {
            return magClientLoseData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            /****1)根据list_item.xml--》得到当前子项元素的布局   【界面】*******/
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView =  LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_mag_client_lose, null);
                //初始化组件
                viewHolder.tv_client_name = (TextView) convertView.findViewById(R.id.tv_client_name);
                viewHolder.tv_client_phoneNumber = (TextView) convertView.findViewById(R.id.tv_client_phoneNumber);
                viewHolder.tv_car_type = (TextView) convertView.findViewById(R.id.tv_car_type);
                viewHolder.tv_handle_time = (TextView) convertView.findViewById(R.id.tv_handle_time);
                viewHolder.tv_salesman_name = (TextView) convertView.findViewById(R.id.tv_salesman_name);
                viewHolder.ll_client_name= (LinearLayout) convertView.findViewById(R.id.ll_client_name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.tv_client_name.setText(magClientLoseData.get(position).getCustomerName());
            viewHolder.tv_client_phoneNumber.setText(magClientLoseData.get(position).getCustormerTel());
            viewHolder.tv_car_type.setText(magClientLoseData.get(position).getCarModel());
            viewHolder.tv_handle_time.setText(magClientLoseData.get(position).getCreateTime());
            viewHolder.tv_salesman_name.setText(magClientLoseData.get(position).getSaleName());

            return convertView;
        }
    }
    static class ViewHolder {
        private TextView tv_client_name;
        private TextView tv_client_phoneNumber;
        private TextView tv_car_type;
        private TextView tv_handle_time;
        private TextView tv_salesman_name;
        private LinearLayout ll_client_name;
    }
}
